//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import { Body, fetch } from '@tauri-apps/api/http';

// {
//     "id": 2841038,
//     "key": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDNkm2o9c13rBd/PCFFF3Ssek2OO4rWQPtZyEmds3cIy/g3gYtcunLdK26w44uyXAatI4bPUGwHulvseec5YE+7j8BEjMKbLGl0JsZ33lcqrac1vK4P3GalDurPFRx+HIUEZ+8VlCQ3r+wfPsdoNO2M+xJYtqHXU9EofY917/sRwzp4m3bOZGtKSy1/hTeCOVmH9+ghr+WyD4gEFktWcOplHABB5ukb0ifZ3Ad9KSh1lVREwieU/W76MFxhWUC35AC0IBN7Hoh380TvW1fvcSKR51QFzG/qQXqXvyPr1ze2Ti/mlRHZP7tl/v+aibfXhFsAEYK5dzhUUQXQ/SV5+z8XN1wZo5HU1GhYntAZvx51Y3xt7MECh4ZanLUl+QUrLt0VfLTKeewlRstCxgS3jRfFOOgEAGhcfMojyewWG9o7GjggorJl1aZyQjBmrvoN4c8vDYG9Om48RlxP1izzrlWjBu2XXqs5AkIGlw0MflPFgXtnDAwBH3VN7AuMuHtIJm8= panlm@DESKTOP-VNGK6KK",
//     "url": "https://gitee.com/api/v5/user/keys/2841038",
//     "title": "panlm@DESKTOP-VNGK6KK",
//     "created_at": "2022-01-06T23:21:04+08:00"
// }

export interface GiteeSshKey {
    key: string;
    id: number;
    title: string;
}

export async function list_ssh_key(accessToken: string): Promise<GiteeSshKey[]> {
    const res = await fetch<GiteeSshKey[]>(`https://gitee.com/api/v5/user/keys?access_token=${accessToken}&per_page=100`, {
        method: "GET",
        timeout: 10,
    });
    if (res.ok && res.status == 200) {
        return res.data;
    } else {
        console.log(res);
        throw "error list user ssh key";
    }
}

export async function add_ssh_key(accessToken: string, title: string, key: string): Promise<void> {
    const res = await fetch<void>(`https://gitee.com/api/v5/user/keys`, {
        method: "POST",
        timeout: 10,
        body: Body.json({
            access_token: accessToken,
            key,
            title,
        }),
    });
    if (res.ok && res.status >= 200 && res.status < 300) {
        return;
    } else {
        console.log(res);
        throw "error add user ssh key";
    }
}

export async function remove_ssh_key(accessToken: string, keyId: string | number): Promise<void> {
    const res = await fetch<void>(`https://gitee.com/api/v5/user/keys/${keyId}?access_token=${accessToken}`, {
        method: "DELETE",
        timeout: 10,
    });
    if (res.ok && res.status  >= 200 && res.status < 300) {
        return;
    } else {
        console.log(res);
        throw "error list user ssh key";
    }
}